package com.xb.myspring.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 批量分割执行
 */
public abstract class BatchSplitUtil {

    public static final int BATCH_SIZE = 2;

    /**
     * 按指定size分割集合，在分批执行cb
     * @param batchList
     * @param cb
     * @param size
     * @param <T>
     */
    public static <T> void split(Collection<T> batchList, Callback<T> cb, int size) {
        if (CollUtil.isEmpty(batchList)) {
            return;
        }
        final List<T> patch = new ArrayList<>(size);
        for (T row : batchList) {
            patch.add(row);
            if (patch.size() == size) {
                cb.execute(patch);
                patch.clear();
            }
        }
        if (!patch.isEmpty()) {
            cb.execute(patch);
            patch.clear();
        }
    }

    public static <T> void split(Collection<T> batchList, Callback<T> cb) {
        split(batchList, cb, BATCH_SIZE);
    }

    public interface Callback<T> {
        void execute(Collection<T> list);
    }


    public static void main(String[] args) {
        ArrayList<Integer> dataList = ListUtil.toList(1,2,3,4,5,6,7,8,9,10);
        BatchSplitUtil.split(dataList, System.out::println);
    }

}
